
import 'dart:ffi';
import 'package:flutter/services.dart';
import 'package:rtk_ota_plugin/rtk_status.dart';
import 'rtk_ota_plugin_platform_interface.dart';

typedef RtkOtaPluginCallBack(RtkStatus type,int progress);
typedef OtaCallBack(String text);

class RtkOtaPlugin {

  ///取消监听
  void disMessage(){
    RtkOtaPluginPlatform.instance.disMessage();
  }

  Future<String?> getPlatformVersion() {
    return RtkOtaPluginPlatform.instance.getPlatformVersion();
  }

  Future<String> md5(String path) async{
    String result =  await RtkOtaPluginPlatform.instance.md5(path);// 1,error message  2,result
    // List<String> ls = result.split(",");
    return result;
  }

  Future<String> getFirmwarePath() async{
    return await RtkOtaPluginPlatform.instance.getFirmwarePath();
  }

  void initDfuAdapter(String address,String path) {
    RtkOtaPluginPlatform.instance.initDfuAdapter(address, path);
  }
  void initIosDfuAdapter(String name,String path) {
    RtkOtaPluginPlatform.instance.initIosDfuAdapter(name, path);
  }
  Future<Void> setAddress(String address) {
    return RtkOtaPluginPlatform.instance.setAddress(address);
  }
  void setFilePath(String path) {
    return RtkOtaPluginPlatform.instance.setFilePath(path);
  }

  Future<String> getColorPath() async {
    return await RtkOtaPluginPlatform.instance.getColorPath();
  }
  Future<String> connectRemoteDevice(String address) {
    return RtkOtaPluginPlatform.instance.connectRemoteDevice(address);
  }

  void otaListener(RtkOtaPluginCallBack callBack){
    RtkOtaPluginPlatform.instance.disMessage();
    RtkOtaPluginPlatform.instance.otaListener((call){
      if(call.method == "sendMessage"){
        String data = call.arguments.toString();
        String d1 = data.split(",")[0];
        // String d2 = data.split(",")[1];
        if(d1 == "1"){
          callBack(RtkStatus.STATUS_CONNECT_SUCC,0);
        }
        if(d1 == "2"){
          callBack(RtkStatus.STATUS_CONNECT_ERROR,0);
        }
        if(d1 == "3"){
          callBack(RtkStatus.STATUS_READY_FINISH,0);
        }
        if(d1 == "4"){
          callBack(RtkStatus.STATUS_OTA_READYING,0);
        }
        if(d1 == "5"){
          callBack(RtkStatus.STATUS_OTA_FINISH,0);
        }
        if(d1 == "6"){
          String d2 = data.split(",")[1];
          callBack(RtkStatus.STATUS_UPGRADING,int.parse(d2));
        }
        if(d1 == "7"){
          callBack(RtkStatus.STATUS_UPGRAD_ERROR,0);
        }
        if(d1 == "8"){
          callBack(RtkStatus.STATUS_UPGRAD_SUCC,0);
        }
        if(d1 == "9"){
          callBack(RtkStatus.STATUS_DEVICE_DIS,0);
        }
        if(d1 == "10"){
          callBack(RtkStatus.STATUS_MAC_NONE,0);
        }
        if(d1 == "11"){
          callBack(RtkStatus.STATUS_DEVICE_CONNECTING,0);
        }
      }
      return callBack(RtkStatus.STATUS_ERROR,0);
    });
  }

  void otaListenerMessage(RtkOtaPluginCallBack callBack){
    RtkOtaPluginPlatform.instance.otaListenerMessage(callBack);
  }
}
